//
//  ShaderManager.cpp
//  SpineTestCpp
//
//  Created by droidhang on 13-6-26.
//
//

#include "ShaderManager.h"

static const char* shaderVertName="public/shader/ccShader_PositionTextureColor_vert.h";
static const char* shaderFragName="public/shader/ccShader_PositionTextureColor_frag%d.h";

ShaderManager* ShaderManager::_pInstance=NULL;

ShaderManager::ShaderManager() {
    _shaderAry=NULL;
}

ShaderManager::~ShaderManager() {
    _shaderAry->release();
}

ShaderManager* ShaderManager::getInstace() {
    if (!_pInstance) {
        _pInstance=new ShaderManager();
    }
    return _pInstance;
}

void ShaderManager::reload() {
    int idx=0;
    CCObject* object;
    CCARRAY_FOREACH(_shaderAry,object) {
        CCGLProgram* shader=(CCGLProgram*) object;
        shader->reset();
        char frag[64];
        sprintf(frag, shaderFragName,idx++);
        shader->initWithVertexShaderFilename(shaderVertName, frag);
        shader->addAttribute(kCCAttributeNamePosition, kCCVertexAttrib_Position);
        shader->addAttribute(kCCAttributeNameColor, kCCVertexAttrib_Color);
        shader->addAttribute(kCCAttributeNameTexCoord, kCCVertexAttrib_TexCoords);
        shader->link();
        shader->updateUniforms();
    }
}

void ShaderManager::load() {
    _shaderAry=CCArray::createWithCapacity(kShader_MAX);
    _shaderAry->retain();
    for (int i=0; i<kShader_MAX; i++) {
        CCGLProgram* shader=new CCGLProgram();
        char frag[64];
        sprintf(frag, shaderFragName,i);
        shader->initWithVertexShaderFilename(shaderVertName, frag);
        shader->addAttribute(kCCAttributeNamePosition, kCCVertexAttrib_Position);
        shader->addAttribute(kCCAttributeNameColor, kCCVertexAttrib_Color);
        shader->addAttribute(kCCAttributeNameTexCoord, kCCVertexAttrib_TexCoords);
        shader->link();
        shader->updateUniforms();
        _shaderAry->addObject(shader);
        shader->autorelease();
    }
}

CCGLProgram* ShaderManager::getShader(ShaderType type) {
    return (CCGLProgram*)_shaderAry->objectAtIndex(type);
}
